<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card shandow="never" class>
        <el-row class="el-card__header">{{
          $route.query.id ? '试题修改' : '试题录入'
        }}</el-row>
        <el-row class="el-card__body">
          <el-form
            :model="quesInputForm"
            label-position="left"
            label-width="100px"
            :rules="rules"
            ref="formRef"
          >
            <el-form-item label="学科" prop="subjectID">
              <el-select
                v-model="quesInputForm.subjectID"
                style="width:400px"
                filterable
                @change="changeSubject"
              >
                <el-option
                  v-for="(item, index) in subjectList"
                  :key="index"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="目录" prop="catalogID">
              <el-select
                v-model="quesInputForm.catalogID"
                style="width:400px"
              >
                <el-option
                  v-for="(item, index) in directorysList"
                  :key="index"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="企业" prop="enterpriseID">
              <el-select v-model="quesInputForm.enterpriseID" style="width:400px" >
                <el-option
                  v-for="(item, index) in enterpriseList"
                  :key="index"
                  :label="item.company"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="城市" prop="city">
              <el-select
                class="filter-item"
                style="width: 198px;marginRight:4px"
                v-model="quesInputForm.province"
                @change="handleProvince"
                filterable
              >
                <el-option
                  v-for="item in citySelect.province"
                  :key="item"
                  :label="item"
                  :value="item"
                ></el-option>
              </el-select>
              <el-select
                class="filter-item"
                style="width: 198px;"
                v-model="quesInputForm.city"
                filterable
              >
                <el-option
                  v-for="item in citySelect.cityDate"
                  :key="item"
                  :label="item"
                  :value="item"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="方向" prop="direction">
              <el-select v-model="quesInputForm.direction" style="width:400px" >
                <el-option
                  v-for="(item, index) in direction"
                  :key="index"
                  :label="item"
                  :value="item"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="题型" prop="questionType">
              <el-radio-group v-model="quesInputForm.questionType">
                <el-radio
                  :key="index"
                  v-for="(item, index) in questionType"
                  :label="item.value + ''"
                  >{{ item.label }}</el-radio
                >
              </el-radio-group>
            </el-form-item>
            <el-form-item label="难度" prop="difficulty">
              <el-radio-group v-model="quesInputForm.difficulty">
                <el-radio
                  :key="index"
                  v-for="(item, index) in difficulty"
                  :label="item.value + ''"
                  >{{ item.label }}</el-radio
                >
              </el-radio-group>
            </el-form-item>
            <el-form-item label="题干" prop="question">
              <quill-editor
                ref="myQuillEditor"
                v-model="quesInputForm.question"
                :options="editorOption"
                style="width:100%;height:200px;marginBottom:50px"
              />
            </el-form-item>
            <!-- 选项组件 -->
            <el-form-item label="选项" prop="checkOptions" v-if="quesInputForm.questionType==1||quesInputForm.questionType==2">
              <question-option
                :questionType="quesInputForm.questionType"
                @get-options="quesInputForm.options = $event"
                :id="id"
              ></question-option>
            </el-form-item>
            <el-form-item label="解析视频">
              <el-input v-model="quesInputForm.videoURL"></el-input>
            </el-form-item>
            <el-form-item label="答案解析" prop="answer">
              <quill-editor
                ref="myQuillEditor"
                v-model="quesInputForm.answer"
                :options="editorOption"
                style="width:100%;height:200px;marginBottom:50px"
              />
            </el-form-item>
            <el-form-item label="题目备注">
              <el-input
                type="textarea"
                :autosize="{ minRows: 4, maxRows: 8 }"
                placeholder
                style="width:400px"
                v-model="quesInputForm.remarks"
              ></el-input>
            </el-form-item>
            <el-form-item label="试题标签" prop="tags">
              <el-select v-model="tags" style="width:400px" multiple >
                <el-option
                  v-for="(item, index) in tagsList"
                  :key="index"
                  :label="item.tagName"
                  :value="item.tagName"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button
                :type="id ? 'success' : 'primary'"
                @click="submitText"
                >{{ this.id ? '确认修改' : '确认提交' }}</el-button
              >
            </el-form-item>
          </el-form>
        </el-row>
      </el-card>
    </div>
  </div>
</template>

<script>
import { provinces, citys } from '@/api/hmmm/citys.js'
import { questionType, difficulty, direction } from '@/api/hmmm/constants'
import { simple as subjectlist } from '../../api/hmmm/subjects'
import { list as enterpriselist } from '../../api/hmmm/companys'
import { simple as directoryslist } from '../../api/hmmm/directorys'
import { add, detail, update } from '../../api/hmmm/questions'
import { list as tagslist } from '../../api/hmmm/tags'
import hljs from 'highlight.js'
import 'highlight.js/styles/tomorrow.css'
import QuestionOption from '../components/question-option'
export default {
  components: { QuestionOption },
  // directives: {
  //   focus: {
  //     inserted(elm) {
  //       elm.focus();
  //     },
  //   },
  // },
  mounted() {
    // 解决富文本编辑器获取焦点使滚动条不在顶部
    this.$refs.myQuillEditor.quill.blur()
    this.$refs.myQuillEditor.quill.enable(false) //刚开始时，不聚焦
    setTimeout(() => {
      this.$refs.myQuillEditor.quill.enable(true) //2秒之后可以点击（聚焦）
    }, 2000)
  },
  data() {
    return {
      rules: {
        // 验证规则
        subjectID: [
          { required: true, message: '请选择学科', trigger: 'change' }
        ],
        catalogID: [
          { required: true, message: '请选择目录', trigger: 'change' }
        ],
        enterpriseID: [
          { required: true, message: '请选择企业', trigger: 'change' }
        ],
        city: [{ required: true, message: '请选择城市', trigger: 'blur' }],
        direction: [
          { required: true, message: '请选择方向', trigger: 'change' }
        ],
        questionType: [
          { required: true, message: '请选择题型', trigger: 'change' }
        ],
        difficulty: [
          { required: true, message: '请选择难度', trigger: 'change' }
        ],
        question: [{ required: true, message: '请输入题干', trigger: 'blur' }],
        answer: [
          { required: true, message: '请输入答案解析', trigger: 'blur' }
        ],
        tags: [{ required: true, message: '请选择标签', trigger: 'blur' }],
        checkOptions: [
          { required: false, message: '请勾选正确答案', trigger: 'blur' }
        ]
      },
      quesInputForm: {
        subjectID: '',
        catalogID: '',
        enterpriseID: '',
        city: '',
        province: '',
        direction: '',
        questionType: '1',
        difficulty: '1',
        question: '',
        options: [],
        videoURL: ' ',
        answer: '',
        remarks: '',
        tags: '',
        isPerfect: ''
      },
      citySelect: {
        province: [],
        cityDate: []
      },
      // 试题标签
      tags: [],
      editorOption: {
        // 富文本编辑器配置
        modules: {
          toolbar: [
            ['bold', 'italic', 'underline', 'strike'], //加粗，斜体，下划线，删除线
            [{ list: 'ordered' }, { list: 'bullet' }], //列表
            ['code-block', 'blockquote'], //引用，代码块
            ['image', 'link'] //上传图片、上传视频
          ],
          syntax: {
            // 高亮配置
            highlight: text => hljs.highlightAuto(text).value
          }
        },
        theme: 'snow'
      },
      subjectList: [],
      directorysList: [],
      enterpriseList: [],
      tagsList: [],
      
    }
  },
  created() {
    // 获取城市
    this.getCityData()
    // 获取学科
    this.getselOptions(subjectlist, null, this.subjectList)
    // 获取企业
    this.getselOptions(enterpriselist, { pageSize: 10000 }, this.enterpriseList)
    // 如果是修改，拿到id获取表单数据，渲染到页面中
    if (this.id) {
      console.log(this.$route.query)
      this.getQuestionById()
    }
  },
  computed: {
    // 挂载常量
    questionType() {
      return questionType
    },
    difficulty() {
      return difficulty
    },
    direction() {
      return direction
    },
    stringTags() {
      // 将试题标签数组转成字符串
      const tags = this.tags.join(',')
      return tags
    },
    id(){
      return this.$route.query.id
    }
  },
  watch:{
    id(){
      this.$router.push('/questions')
      this.$nextTick(()=>{
        this.$router.push('/questions/new')
      })
    }
  },
  methods: {
    async getQuestionById() {
      // 修改模式时获取id渲染页面;
      try {
        const { data: res } = await detail({ id: this.id })

        console.log(res)
        this.tags = res.tags.split(',')
        //  修改时视频解析不能为空，迷惑操作
        res.videoURL = res.videoURL || ' '
        this.quesInputForm = res
        // 一开始要根据学科id渲染目录和标签列表
        this.getselOptions(
          directoryslist,
          { subjectID: res.subjectID },
          this.directorysList
        )
        this.getselOptions(
          tagslist,
          { subjectID: res.subjectID },
          this.tagsList
        )
      } catch (err) {
        console.log(err)
      }
    },
    // 获取市
    getCityData: function() {
      this.citySelect.province = provinces()
    },
    // 选市获取到区
    handleProvince: function(e) {
      this.citySelect.cityDate = citys(e)
      // 默认第一个区
      this.quesInputForm.city = this.citySelect.cityDate[0]
    },
    async getselOptions(fn, params, list) {
      // 封装请求
      const { data: res } = await fn(params)
      if (list === this.enterpriseList || list === this.tagsList) {
        list.push(...res.items)
      } else {
        list.push(...res)
      }
    },
    changeSubject() {
      // 学科选择获取目录和标签
      this.directorysList = []
      this.tagsList = []
      this.tags = []
      if (!this.quesInputForm.subjectID) return
      this.getselOptions(
        directoryslist,
        { subjectID: this.quesInputForm.subjectID },
        this.directorysList
      )
      this.getselOptions(
        tagslist,
        { subjectID: this.quesInputForm.subjectID },
        this.tagsList
      )
    },
    submitText() {
      // 点击提交
      this.quesInputForm.tags = this.stringTags
      // 先进行表单验证;
      this.$refs.formRef.validate(async valid => {
        if (!valid) {
          this.$message({
            message: '请输入完整信息',
            type: 'error'
          })
          return false
        }
        try {
          console.log(this.quesInputForm)
          if (this.id) {
            // 提交修改
            const { data: res } = await update(this.quesInputForm)
            this.$message.success('试题修改成功')
          } else {
            // 提交新题
            const { data: res } = await add(this.quesInputForm)
            this.$message.success('试题录入成功')
          }
          this.$router.push('/questions/list')
        } catch (err) {
          console.log(err)
          if (err.response.status == 500) {
            this.$message.error('题干过长')
          }
        }
      })
    }
  }
}
</script>

<style scoped lang="scss">
.app-container {
  ::v-deep.el-card__body {
    &:nth-child(1) {
      padding: 0;
    }
  }
}
</style>
